package com.xinxing.learning.batch.increment.step;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinxing.learning.batch.common.LogConstants;
import com.xinxing.learning.batch.common.SyncConstants;
import com.xinxing.learning.batch.entity.User;
import com.xinxing.learning.batch.mapper.origin.OriginUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.database.AbstractPagingItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class IncrementUserItemReader extends AbstractPagingItemReader<User> {
    protected Map<String, Object> params;

    @Autowired
    private OriginUserMapper originUserMapper;

    @Value("#{jobParameters['user']}")
    public String user;

    @Value("#{jobParameters['time']}")
    public Long time;

    public IncrementUserItemReader() {
        // 不设置默认是10
        this.setPageSize(2);
    }

    @Override
    protected void doReadPage() {
        log.info(LogConstants.LOG_TAG + "user:{},time:{}", user, time, params);
        // List<User> originIncrUser = originUserMapper.getOriginIncrUser(params);
        int page = this.getPage() + 1;
        int pageSize = this.getPageSize();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.ge(Objects.nonNull(params.get(SyncConstants.STR_LAST_UPDATE_TIME)), User::getSysCreateTime, params.get(SyncConstants.STR_LAST_UPDATE_TIME))
                .or()
                .ge(Objects.nonNull(params.get(SyncConstants.STR_LAST_UPDATE_TIME)), User::getSysUpdateTime, params.get(SyncConstants.STR_LAST_UPDATE_TIME));
        // Page<User> userPage = originUserMapper.selectPage(new Page<>(page, pageSize), null);
        Page<User> userPage = originUserMapper.selectPage(new Page<>(page, pageSize), userLambdaQueryWrapper);
        List<User> userList = userPage.getRecords();

        if (this.results == null) {
            this.results = new CopyOnWriteArrayList<>();
        } else {
            this.results.clear();
        }

        this.results.addAll(userList);
    }

    @Override
    protected void doJumpToPage(int i) {

    }

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }
}
